package com.factory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-02-28.
 *
 * @author zhoufy
 */
public class BeanFactory {


    private static BeanFactory beanFactory = new BeanFactory();

    public static BeanFactory getInstance() {
        return beanFactory;
    }

    /**
     * 读取xml配置文件，通过反射实例化对象 并存储到map中
     * 对外部提供获取实例化对象的方法
     */

    private static Map<String, Object> map = new HashMap<>();

    static {
        //  加载 beans.xml 配置文件
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");

        //  dom4j 解析配置文件
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> beanList = rootElement.selectNodes("//bean");

            for (Element element : beanList) {
                //  获取 bean标签的 id 和class 通过class.forName() 加载类 id作为key存入map中
                String id = element.attributeValue("id");
                String className = element.attributeValue("class");
                Class<?> clazz = Class.forName(className);
                Object bean = clazz.newInstance();
                map.put(id, bean);
            }

            //  实例化之后维护对象之间的关系
            List<Element> properties = rootElement.selectNodes("//property");
            for (Element property : properties) {
                String name = property.attributeValue("name");
                String ref = property.attributeValue("ref");

                //  找到父元素
                String parentId = property.getParent().attributeValue("id");
                // 获取到父元素对象
                Object parentObject = map.get(parentId);

                // 遍历父元素的方法
                Method[] declaredMethods = parentObject.getClass().getDeclaredMethods();
                boolean flag = true;
                for (Method declaredMethod : declaredMethods) {
                    // 该方法就是 setAccountDao(AccountDao accountDao)
                    if (declaredMethod.getName().equalsIgnoreCase("set" + name)) {
                        declaredMethod.invoke(parentObject, map.get(ref));
                        flag = false;
                    }
                }
                if(flag){
                    // 获取一下上层父类 简单递归一下
                    Method[] parentDeclaredMethods = parentObject.getClass().getSuperclass().getDeclaredMethods();
                    for (Method declaredMethod : parentDeclaredMethods) {
                        if (declaredMethod.getName().equalsIgnoreCase("set" + name)) {
                            declaredMethod.invoke(parentObject, map.get(ref));
                        }
                    }
                }
                // 把处理之后的parentObject重新放到map中
                map.put(parentId, parentObject);

            }
        } catch (DocumentException | ClassNotFoundException | IllegalAccessException | InstantiationException
                | InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    public Object getObject(String id) {
        return map.get(id);
    }
}
